#include "sk_circle_shape.h"
#include "sk_creation_params.h"

#include <QDomDocument>
#include <QDomElement>

#include <Box2D.h>

namespace sk
{

    CircleShape::CircleShape()
    {
    }

    b2Body * CircleShape::addToWorld(b2World * world)
    {
        b2BodyDef bd = bodyDef;
        bd.position.Set( (bd.position.x + r)* PIXEL_TO_METERS, (bd.position.y + r) * PIXEL_TO_METERS);
        b2Body * body = world->CreateBody(&bd);
        b2CircleShape s;
        s.m_radius = r * PIXEL_TO_METERS;
        fixtureDef.shape = &s;
        body->CreateFixture(&fixtureDef);
        return body;
    }

    GameShape * CircleShape::clone()
    {
        CircleShape * res = new CircleShape();
        res->bodyDef = bodyDef;
        res->fixtureDef = fixtureDef;
        res->r = r;
        return res;
    }

    int CircleShape::type()
    {
        return IT_SIMPLE_CIRCLE;
    }

    void CircleShape::setData(void * params)
    {
        SimpleCircleParam * p = static_cast<SimpleCircleParam *>(params);
        r = p->r;
    }

    void CircleShape::serialiseCustomShapeData(QDomDocument * doc, QDomElement * e)
    {
        QDomElement customShapeElement = doc->createElement("customShapeData");
        customShapeElement.setAttribute("radius", r);
        e->appendChild(customShapeElement);
    }

    bool CircleShape::deserialiseCustomShapeData(QDomElement * e)
    {
        for (int i = 0; i < e->childNodes().count(); ++i)
        {
            QDomElement ee = e->childNodes().at(i).toElement();
            if (ee.tagName() == "customShapeData")
            {
                r = ee.attribute("radius").toFloat();
                return true;
            }
        }
        return false;
    }

    QString CircleShape::xmlType()
    {
        return CircleShape::XmlType();
    }

    QString CircleShape::XmlType()
    {
        return "circleShape";
    }

}   // namespace sk
